// personal_center/pages/addressManagement/index.js

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    list: [],
    loading: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.get_address()
  },
  onChange(e) {
    this.setData({
      active: e.detail.index,
      list: []
    })
    this.get_address()
  },
  add_address() {
    wx.navigateTo({
      url: '/personal_center/pages/add_abroad_address/index?type=' + this.data.active,
    })
  },
  get_address() {
    const that = this;
    that.setData({
      loading: true
    })
    app.wxRequest('/api/Address/index', {
      page: 1,
      type: that.data.active
    }, function (res) {
      if (res.code == 200) {
        let list = res.data;
        if (list.length > 0) {
          list = list.map(item => {
            return {
              checked: item.default ? true : false,
              ...item
            }
          })
        }
        that.setData({
          list: list,
          loading: false
        })
      } else {
        app.toast(res.message)
        that.setData({
          loading: false
        })
      }
    })
  },
  change_checked(e) {
    if(!e.detail){
      return false
    }
    const that=this
    let index = e.currentTarget.dataset.index;
    let list = this.data.list;
    list=list.map(item=>{
      return{
        ...item,
        checked:false
      }
    })
    app.loading()
    app.wxRequest('/api/Address/updateDefault', {
      id: list[index].id
    }, function (res) {
      if (res.code == 200) {
        list[index].checked = !list[index].checked
        that.setData({
          list: list
        })
      } else {
        app.toast(res.message)
      }
    })
  },
  editor(e) {
    let index = e.currentTarget.dataset.index;
    wx.setStorageSync('address_item0', this.data.list[index])
    wx.navigateTo({
      url: '/personal_center/pages/add_abroad_address/index?type=' + this.data.active,
    })
  },
  delete(e) {
    let index = e.currentTarget.dataset.index;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})